package com.uujava.minibox.actionstyle;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

/**
 * 
 * @category 窗体特效 窗体靠边吸附
 * @version 2.0
 * @author k
 * @since 2012-10-23 修正2013-2-16
 */
public class WindowSnapper implements MouseMotionListener{

	private int snap_distance = 20;//吸附距离
	private JFrame jframe=null;
	
	public int getSnap_distance() {
		return snap_distance;
	}

	/**
	 * @category功能窗体靠边吸附
	 * @param snap_distance 靠边吸附距离 
	 */
	public void setSnap_distance(int snap_distance) {
		this.snap_distance = snap_distance;
	}
	
	public WindowSnapper(JFrame jframe){
		this.jframe=jframe;
	}
	final Dimension size = Toolkit.getDefaultToolkit().getScreenSize();//获得系统分辨率
	public void windowMoved(JFrame jframe) {
		int systemWidth=(int) size.getWidth();//宽
		int systemHeight=(int) size.getHeight();
		
		//获得窗体的左上角位置
		int nx = jframe.getX();
		int ny = jframe.getY();
		//防止此方法多次被執行浪費cpu，如果窗體易吸附則跳出方法
		if(nx==0||ny==0||(systemWidth-nx==jframe.getWidth()))
			return;
		
		// top
		if (ny < 0 + snap_distance) {
			ny = 0;
		}
		// left
		if (nx < 0 + snap_distance) {
			nx = 0;
		}
		// right
		if (nx > systemWidth - jframe.getWidth()
				- snap_distance) {
			nx = systemWidth - jframe.getWidth();
		}
		// bottom
		if (ny > systemHeight - jframe.getHeight()
				- snap_distance) {
			ny = systemHeight - jframe.getHeight();
		}
		
		jframe.setLocation(nx, ny);//设置窗体移动到的位置
		
	}

	public static void main(String[] args) {
		JFrame frame = new JFrame("边界吸附");
		JLabel label = new JLabel(
				"边界吸附 窗体测试");
		frame.getContentPane().add(label);
		frame.setSize(300,450);
		
		frame.setBounds(100, 100,frame.getWidth(),frame.getHeight());
		frame.addMouseMotionListener(new WindowSnapper(frame));
		frame.setVisible(true);
	}

	@Override
	public void mouseDragged(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseMoved(MouseEvent e) {
		// TODO Auto-generated method stub
		windowMoved(jframe);//窗体靠边吸附
	}

	
}
